import Config from './../http/Config'
import ComApiHttp from './../http/comApiHttp'
import Util from './../utils/util.class'
import router from './../router'

export default class Login {
  static PuCodeUri = Config.openApiUrl + '/passport/authen/pu-code'; // 授权码uri
  static EuTokenUri = Config.openApiUrl + '/passport/authen/eu-token'; // token uri
  static RefreshTokenUri = Config.openApiUrl + '/passport/authen/eu-retoken'; // 置换新令牌 uri
  static WhoamiUri = Config.openApiUrl + '/memberUser/whoami'; //   我是谁 uri
  static EuByeUri = Config.openApiUrl + '/passport/authen/eu-bye';  //注销登录状态
  static appId = Config.appId;
  static appKey = Config.appKey;
  static APP_SECRET = Config.appSecret;

  //密码加密处理
  static getEncrypt (str, key = '') {
    let encrypt = new JSEncrypt();
    encrypt.setPublicKey(key);
    str = str + "##" + new Date().getTime();
    return encrypt.encrypt(str);
  }

  //获取授权码grantCode然后利用授权码 去获得token
  static getPuCode (username, password) {
    return new Promise((resolve, reject) => {
      ComApiHttp.openApiAxios({
        url: this.PuCodeUri,
        data: {
          appId: this.appId,
          loginAccount: username,
          password: this.getEncrypt(password, this.appKey)
        },
        success: (data) => {
          let grantCode = data.result.grantCode;
          let appSecret = this.getEncrypt(this.APP_SECRET, this.appKey);
          ComApiHttp.openApiAxios({
            url: this.EuTokenUri,
            data: {
              appId: this.appId, // appId
              appSecret: appSecret,
              grantCode: grantCode
            },
            success: (res) => {
              let data = res.result;
              this.setUserInfor(data);

              resolve(data);
            }
          })
        }
      })
    })
  }

  //退出登录
  static quitLogin () {
    let userId = Util.getSessionStorage('userId');
   return new Promise((resolve)=>{
     ComApiHttp.openApiAxios({
         url: this.EuByeUri,
         data: {
           appId: this.appId, // appId
           userId: userId // 用户标识
         },
         success: (data) => {
           resolve(data)
         }
     });
   })
  }
  static setUserInfor(data){
    /*accessTokenExpire:后台过期时间半小时 refreshTokenExpire：后台过期时间为7个小时*/
    let accessTokenExpire = Util.getCurrentSecondTime() + data.accessTokenExpire - (1000 * 10);// 前端设置比后台早1分钟
    let refreshTokenExpire = Util.getCurrentSecondTime() + data.refreshTokenExpire - (1000 * 10);// 前端设置比后台早1分钟
    Util.setLocalStorage('accessToken', data.accessToken, accessTokenExpire);//保存accessToken
    Util.setSessionStorage('accessToken', data.accessToken, accessTokenExpire);//保存accessToken
    Util.setLocalStorage('refreshToken', data.refreshToken, refreshTokenExpire);//保存refreshToken
    Util.setSessionStorage('refreshToken', data.refreshToken, refreshTokenExpire);//保存refreshToken
    Util.setSessionStorage('userId', data.userId);
  }
  //获取个人信息
  static getToken (success, error) {

    let accessToken = Util.getLocalStorage('accessToken');//获取accessToken
    let refreshToken = Util.getSessionStorage('refreshToken');//获取accessToken
    let userId = Util.getSessionStorage('userId');//获取用户id
    if (!userId) {
        this.goLogin();
    } else if (!accessToken) {
      console.log('accessToken无效')
      this.RefreshAccessToken(refreshToken, userId, success); // 获取最新的AccessToken
    } else {
      console.log('accessToken有效')
      success(accessToken, userId, refreshToken);
    }
  }

  //置换新令牌
  static RefreshAccessToken (refreshToken , userId , success){
    ComApiHttp.openApiAxios({
      url : this.RefreshTokenUri,
      data : {
        appId : this.appId, // appId
        appSecret : this.getEncrypt(this.APP_SECRET,this.appKey) , // 业务应用秘钥，带时间戳加密的形式
        refreshToken : refreshToken, // 刷新令牌
        userId : userId // 用户标识
      },
      success :  (res) => {
        let data = res.result;
        this.setUserInfor(data);
        success(data.accessToken, data.userId, refreshToken);
      }
    });
  }
  //去登录
  static goLogin () {
    // 单页面登录会有问题
    router.push({
      path: '/system/login'
    })
  }
  //检测登录信息是否有效 ===== 拦截器
  static checkLogin (success, error = null) {
    this.getToken((accessToken, userId, refreshToken) => {
      ComApiHttp.openApiAxios({
            url: this.WhoamiUri,
            data: {
              appId: this.appId, // appId
              accessToken: accessToken, // 刷新令牌
              userId: userId // 用户标识
            },
            success: (res) => {
              let data = res.data;
              console.log(data)

              success();
              Util.getSessionStorage('userInfo');

            }
          });
        }
    )
  }
}
